package controller

import (
	bc "Agricultural/application/blockchain"
	"Agricultural/application/lib"
	"Agricultural/application/util"
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

func UploadImg(ctx *gin.Context)  {
	file, _ := ctx.FormFile("imgFile")
	companyId := ctx.PostForm("companyId")
	filename := companyId + "_" + util.Krand(6, 0) + ".png"
	req := new(lib.CompanyImg)
	if err := ctx.ShouldBind(req); err != nil {
		_ = ctx.AbortWithError(http.StatusBadRequest, err)
		return
	}
	req.Id = util.Krand(11, 0)
	req.ImgName = filename
	req.Subjection = companyId
	fmt.Println(req)
	marshal, _ := json.Marshal(req)
	if err := ctx.SaveUploadedFile(file, "/home/work/go/src/Agricultural/image/" + filename); err != nil {
		return
	}
	resp, err := bc.ChannelExecute("uploadImg", [][]byte{
		marshal,
		[]byte(companyId),
	})
	if err != nil {
		fmt.Println("ERROR: " , err.Error())
		ctx.String(http.StatusInternalServerError, err.Error())
		return
	}
	ctx.JSON(http.StatusOK, resp)
}

func SendCompanyImg(ctx *gin.Context)  {
	imgPath := ctx.Query("imgPath")
	resp, err := bc.ChannelQuery("sendCompanyImg", [][]byte{
		[]byte(imgPath),
	})
	if err != nil {
		fmt.Println("ERROR: ", err.Error())
		ctx.String(http.StatusInternalServerError, err.Error())
		return
	}
	ctx.File(bytes.NewBuffer(resp.Payload).String())
}